<?php
namespace app\api\controller;

use app\common\controller\ApiController;
use think\App;
use think\facade\Db;
use app\api\controller\Shop;
use tidy;

class Test extends ApiController
{
    protected $noNeedLogin = ['add_htreview','edit_htreview'];
    protected $mustLogin = ["add_htreview","edit_htreview"];

    use \app\admin\traits\Curd;
    public function __construct(App $app)
    {
        parent::__construct($app);
    }
 
    
    /**
     * 获取token
     */
    public function corpAccessToken()
    {
        $method = 'POST';
        $appId = 'FSAID_131aba6';
        $appSecret = '69a6c56e23234bc9b56992f1468d103a';
        $permanentCode = 'F7BE99269E4BFC33400A92D039A3E28F';
        $url = 'https://open.fxiaoke.com/cgi/corpAccessToken/get/V2';
        $header = [
                         'Content-Type:application/json'
                   ];
        $res =  json_encode(compact('appId', 'appSecret', 'permanentCode'));
        $data = $this->http_curl($url,$method, $res, $header, $timeout = 10); 
         
        if(!empty($data) && isset($data) && $data['errorCode'] ==0 && $data['errorMessage'] == 'success' )
        {
            $data['addtime'] = time();
            if(Db::name('atoken')->where('id',1)->find())
            {
               $zxc = Db::name('atoken')->where('id',1)->update($data);  
            }else{
               $zxc = Db::name('atoken')->insert($data);  
            }
           return $data;
        }
        
    }

    /**
    * 获取   合同变更明细  
    */
    public function bgquery($contract_id)
    {
        $qwe = $this->corpAccessToken();
        $url = 'https://open.fxiaoke.com/cgi/crm/custom/v2/data/query';
        $corpAccessToken = $qwe['corpAccessToken'];
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';
        $data = [ 'search_query_info'=>[
            'offset'=>0, 
            'limit'=>100, 
            'filters'=>[
                [ 
                    'field_name'=>'field_igh0c__c',
                    'field_values'=>[$contract_id],
                    'operator'=>'EQ' 
                ]
                // ,
                // [ 
                //     'field_name'=>'record_type',
                //     'field_values'=>"record_4M1qz__c",
                //     'operator'=>'EQ'
                // ]
            ]
         ],
         'dataObjectApiName'=>'object_aKd4c__c'
        ];
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'));
      
        $method = 'POST';
         $header = [
                         'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
        if(!empty($dsdf) && $dsdf['errorDescription'] == 'success' && !empty($dsdf['data']) && !empty($dsdf['data']['dataList']))
        {
             $tyu = $this->bgrecord($dsdf['data']['dataList']);
             return $tyu;
        }
    }

     /**
      * 数据重组 处理  
      */
      public function bgrecord($dataList)
      {
          $list = [];
          foreach ($dataList as $v)
          { 
            $data = [
                'field_rx8D6__c'     =>   !empty($v['field_rx8D6__c__r']) ? $v['field_rx8D6__c__r'] :'', //合同明细
                'field_5sgn7__c'     =>   !empty($v['field_5sgn7__c']) ? $v['field_5sgn7__c'] :'', //跟踪号
                'field_6wshK__c'     =>   !empty($v['field_6wshK__c']) ? $v['field_6wshK__c'] :'',//交货期
                'field_vGl2D__c'     =>   !empty($v['field_vGl2D__c']) ? $v['field_vGl2D__c'] :'', //合同金额（元）
                'field_91Hqs__c'     =>   !empty($v['field_91Hqs__c']) ? $v['field_91Hqs__c'] :'', //产品数量
                'field_faqJ1__c'     =>   !empty($v['field_faqJ1__c']) ? $v['field_faqJ1__c'] :'', //产品型号
                'field_3g11a__c'     =>   !empty($v['field_3g11a__c']) ? $v['field_3g11a__c'] :'', //是否有监测器
                'field_O31OR__c'     =>  !empty($v['field_O31OR__c']) ? $v['field_O31OR__c'] :'', //监测器型号/计数器型号
                'field_z1WhU__c'     =>   !empty($v['field_z1WhU__c']) ? $v['field_z1WhU__c'] :'',//工厂代号
                'field_M616j__c'     =>   !empty($v['field_M616j__c']) ? $v['field_M616j__c'] :'',//监测器工厂代号
                'field_qpHQm__c'     =>   !empty($v['field_qpHQm__c']) ? $v['field_qpHQm__c'] :'',//户内/户外
                'field_6MDbq__c'     =>   !empty($v['field_6MDbq__c']) ? $v['field_6MDbq__c'] :'', //油漆颜色
                'field_Nhd76__c'     =>   !empty($v['field_Nhd76__c']) ? $v['field_Nhd76__c'] :'', //避雷器工程BOM/标准BOM
                'field_jBst7__c'     =>   !empty($v['field_jBst7__c']) ? $v['field_jBst7__c'] :'', //监测器工程BOM/标准BOM
                'field_PkEk8__c'     =>   !empty($v['field_PkEk8__c']) ? $v['field_PkEk8__c'] :'', //盆子颜色
                'field_v61hO__c'     =>   !empty($v['field_v61hO__c']) ? $v['field_v61hO__c'] :'', //装箱单类型
                'field_x7x8k__c'     =>   !empty($v['field_x7x8k__c']) ? $v['field_x7x8k__c'] :'', //其他要求
            ];
            
               $data['field_6wshK__c'] = date("Y-m-d H:i:s",substr($v['field_6wshK__c'],0,10));//交货期
               //是否有监测器
               if($data['field_3g11a__c'] == "2m3ij64V6"){
                    $data['field_3g11a__c'] = "是";
                }elseif($data['field_3g11a__c'] == "option1"){
                        $data['field_3g11a__c'] = "否";
                }else{
                    $data['field_3g11a__c'] = "";
                }
                //避雷器工程BOM/标准BOM
                if($data['field_Nhd76__c'] == "6k8by2ex8"){
                    $data['field_Nhd76__c'] = "工程BOM";
                }elseif($data['field_Nhd76__c'] == "I8oG1P1Oc"){
                    $data['field_Nhd76__c'] = "标准BOM";
                }elseif($data['field_Nhd76__c'] == "2wj1D10mt"){
                    $data['field_Nhd76__c'] = "外购";
                }elseif($data['field_Nhd76__c'] == "t0svnOp7O"){
                    $data['field_Nhd76__c'] = "改制";
                }else{
                    $data['field_Nhd76__c'] = "";
                }
                //监测器工程BOM/标准BOM
                if($data['field_jBst7__c'] == "45Piqt5yP"){
                    $data['field_jBst7__c'] = "工程BOM";
                }elseif($data['field_jBst7__c'] == "d6qol41EK"){
                    $data['field_jBst7__c'] = "标准BOM";
                }elseif($data['field_jBst7__c'] == "lSv5R5253"){
                    $data['field_jBst7__c'] = "外购";
                }elseif($data['field_jBst7__c'] == "nFIdGkDxq"){
                    $data['field_jBst7__c'] = "改制";
                }else{
                    $data['field_jBst7__c'] = "";
                }
               
            
              if($data['field_qpHQm__c'] == "042QqX041"){
                    $data['field_qpHQm__c'] = "户内";
              }elseif($data['field_qpHQm__c'] == "option1"){
                    $data['field_qpHQm__c'] = "户外";
              }else{
                $data['field_qpHQm__c'] = "";
              }

             
            array_push($list,$data);
          }
          return $list;
      }

   
    /**
    * 获取  对象列表数据   合同评审明细  6296ff1f49a8e80001f2a452
    */
    public function query($contract_id)
    {
        $qwe = $this->corpAccessToken();
        $url = 'https://open.fxiaoke.com/cgi/crm/custom/v2/data/query';
        $corpAccessToken = $qwe['corpAccessToken'];
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';
        $data = [ 'search_query_info'=>[
            'offset'=>0, 
            'limit'=>100, 
            'filters'=>[
                [ 
                    'field_name'=>'field_Ih1oo__c',
                    'field_values'=>[$contract_id],
                    'operator'=>'EQ' 
                ]
            ]
         ],
         'dataObjectApiName'=>'object_KPDfn__c'
        ];
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'));
      
        $method = 'POST';
         $header = [
                         'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
        if(!empty($dsdf) && $dsdf['errorDescription'] == 'success' && !empty($dsdf['data']) && !empty($dsdf['data']['dataList']))
        {
             $tyu = $this->record($dsdf['data']['dataList']);
             return $tyu;
        }
    }

     /**
      * 数据重组 处理  629ae0e049a8e800017094e6
      */
      public function record($dataList)
      {
          $list = [];
          foreach ($dataList as $v)
          {
            $data = [
                'materialNum'     =>   !empty($v['field_I6T2f__c']) ? $v['field_I6T2f__c'] :'', //工厂代号
                'promodel'     =>   !empty($v['field_6Bsd0__c']) ? $v['field_6Bsd0__c'] :'', //产品型号
                'num'     =>   !empty($v['field_qe6hL__c']) ? $v['field_qe6hL__c'] :'',//数量
                'trackNumberTxt'     =>   !empty($v['field_q5nC6__c']) ? $v['field_q5nC6__c'] :'', //跟踪号（新）
                'techniComplete'     =>   !empty($v['field_58zJ1__c']) ? $v['field_58zJ1__c'] :'', //技术完成日期
                'produceComplete'     =>   !empty($v['field_xUru6__c']) ? $v['field_xUru6__c'] :'', //生产完成日期
                'materialReturn'     =>   !empty($v['field_41muz__c']) ? $v['field_41muz__c'] :'', //物资回厂日期
                'bomProperty'     =>   '', //BOM属性 -
                'externalInsulation'     =>   '', //外绝缘部件号码 -
                'relationBillNo'     =>  !empty($v['field_Ej3uK__c']) ? $v['field_Ej3uK__c'] :'', //联系单编号
                'bomBatch'     =>  '', //BOM批次 -
                'paintColor'     =>   !empty($v['field_B2mZt__c']) ? $v['field_B2mZt__c'] :'',//油漆颜色
                'basinColor'     =>   !empty($v['field_1z3N2__c']) ? $v['field_1z3N2__c'] :'',//盆子颜色
                'inAndOutDoor'     =>   !empty($v['field_0sAvt__c']) ? $v['field_0sAvt__c'] :'',//户内/户外
                'remark'     =>   !empty($v['field_lfE42__c']) ? $v['field_lfE42__c'] :'', //备注
                'detailNumber'     =>   !empty($v['name']) ? $v['name'] :'', //明细序号
                'productClass'     =>   !empty($v['field_S448k__c']) ? $v['field_S448k__c'] :'', //产品分类
                'voltageLevel'     =>   !empty($v['field_cs28f__c']) ? $v['field_cs28f__c'] :'', //电压等级
                'measurementUnit'     =>   !empty($v['field_mThRf__c']) ? $v['field_mThRf__c'] :'', //计量单位
                'unitPrice'     =>   !empty($v['field_i9Kdg__c']) ? $v['field_i9Kdg__c'] :'', //单价
                'amount'     =>   !empty($v['field_79qq5__c']) ? $v['field_79qq5__c'] :'', //新签合同额
                'isHasMonitor'     =>   !empty($v['field_gA0C7__c']) ? $v['field_gA0C7__c'] :'', //是否有监测器
                'monitorModel'     =>   !empty($v['field_R6gro__c']) ? $v['field_R6gro__c'] :'', //监测器型号/计数器型号
                'sparePartIdent'     =>   !empty($v['field_ttW4J__c']) ? $v['field_ttW4J__c'] :'', //备品标识
                'deliveryDate'     =>   !empty($v['field_2gOKk__c']) ? $v['field_2gOKk__c'] :'', //交货期（预计）
                'isPreProduct'     =>   !empty($v['field_5cs54__c']) ? $v['field_5cs54__c'] :'', //是否已经预投
                'objID'     =>   !empty($v['field_tRHPn__c']) ? $v['field_tRHPn__c'] :'',//实物ID号码段
                'packingListType'     =>   !empty($v['field_93cav__c']) ? $v['field_93cav__c'] :'',//装箱单类型 
            ];
            
               $data['deliveryDate'] = date("Y-m-d H:i:s",substr($v['field_2gOKk__c'],0,10));//交货期（预计）
               $data['techniComplete'] = date("Y-m-d H:i:s",substr($v['field_58zJ1__c'],0,10));//技术完成日期
               $data['produceComplete'] = date("Y-m-d H:i:s",substr($v['field_xUru6__c'],0,10));//生产完成日期
               $data['materialReturn'] = date("Y-m-d H:i:s",substr($v['field_41muz__c'],0,10));//物资回厂日期
               //备品标识
               if($data['sparePartIdent'] == "Q6FeSFGwH"){
                    $data['sparePartIdent'] = "是";
                }elseif($data['sparePartIdent'] == "option1"){
                        $data['sparePartIdent'] = "否";
                }else{
                    $data['sparePartIdent'] = "";
                }
                //是否已经投预
               if($data['isPreProduct'] == "2d0SjjmK5"){
                    $data['isPreProduct'] = "是";
                }elseif($data['isPreProduct'] == "option1"){
                    $data['isPreProduct'] = "否";
                }else{
                    $data['isPreProduct'] = "";
                }
                //计量单位
                if($data['measurementUnit'] == "fncSfUb8q"){
                    $data['measurementUnit'] = "PCS";
                }elseif($data['measurementUnit'] == "D61Xhr0nv"){
                    $data['measurementUnit'] = "个";
                }elseif($data['measurementUnit'] == "znacm37PE"){
                    $data['measurementUnit'] = "套";
                }elseif($data['measurementUnit'] == "SIrbbQ9ct"){
                    $data['measurementUnit'] = "组";
                }elseif($data['measurementUnit'] == "iDEGi2Ofh"){
                    $data['measurementUnit'] = "台";
                }else{
                    $data['measurementUnit'] = "";
                }
            
              if($data['inAndOutDoor'] == "042QqX041"){
                    $data['inAndOutDoor'] = "户内";
              }elseif($data['inAndOutDoor'] == "option1"){
                    $data['inAndOutDoor'] = "户外";
              }else{
                $data['inAndOutDoor'] = "";
              }

            //电压等级
            if($data['voltageLevel'] == "option1"){
                $data['voltageLevel'] = "1000kv";
            }elseif($data['voltageLevel'] == "XN7Jy427p"){
                    $data['voltageLevel'] = "750";
            }elseif($data['voltageLevel'] == "IV55pooHe"){
                    $data['voltageLevel'] = "500kv";
            }elseif($data['voltageLevel'] == "BQxc02cvd"){
                    $data['voltageLevel'] = "330kv";
            }elseif($data['voltageLevel'] == "AN25q2WZp"){
                    $data['voltageLevel'] = "220kv";
            }elseif($data['voltageLevel'] == "eqNV1fg3A"){
                    $data['voltageLevel'] = "110kv";
            }elseif($data['voltageLevel'] == "HOi2I1dvB"){
                    $data['voltageLevel'] = "35kv";
            }elseif($data['voltageLevel'] == "A7XK22GFm"){
                    $data['voltageLevel'] = "10kv及以下";
            }elseif($data['voltageLevel'] == "1u2x7sGoi"){
                    $data['voltageLevel'] = "±110kv";
            }elseif($data['voltageLevel'] == "qyhgP2Xkz"){
                    $data['voltageLevel'] = "±800kv";
            }elseif($data['voltageLevel'] == "S1753nSuL"){
                    $data['voltageLevel'] = "±500kv";
            }elseif($data['voltageLevel'] == "pDHj4WMwc"){
                    $data['voltageLevel'] = "±400kv";
            }elseif($data['voltageLevel'] == "BN6dp1g16"){
                    $data['voltageLevel'] = "±300kv";
            }elseif($data['voltageLevel'] == "ztekaB50v"){
                    $data['voltageLevel'] = "±100kv及以下";
            }elseif($data['voltageLevel'] == "T7oB1ncMX"){
                    $data['voltageLevel'] = "100kv以下";
            }elseif($data['voltageLevel'] == "f8Re1oUjE"){
                    $data['voltageLevel'] = "无";
            }else{
                $data['voltageLevel'] = "";
            }

            //产品分类
            if($data['productClass'] == "mCd2b0tYj"){
                $data['productClass'] = "瓷壳避雷器";
            }elseif($data['productClass'] == "06kSrfa31"){
                $data['productClass'] = "复合避雷器";
            }elseif($data['productClass'] == "b4q19V1vM"){
                $data['productClass'] = "罐式避雷器";
            }elseif($data['productClass'] == "Y5Ja43vq7"){
                $data['productClass'] = "直流避雷器";
            }elseif($data['productClass'] == "hv6f5e0UF"){
                $data['productClass'] = "复合套管";
            }elseif($data['productClass'] == "1eFOiLkBO"){
                $data['productClass'] = "监测器";
            }elseif($data['productClass'] == "U8FjUkj81"){
                $data['productClass'] = "电阻片";
            }elseif($data['productClass'] == "dEU11vO3j"){
                $data['productClass'] = "设备集成";
            }elseif($data['productClass'] == "5j7NJaLj1"){
                $data['productClass'] = "增值服务";
            }elseif($data['productClass'] == "kZ1bo5RpC"){
                $data['productClass'] = "瓷套套管装配";
            }elseif($data['productClass'] == "j56o8D5an"){
                $data['productClass'] = "复合套管装配";
            }else{
                $data['productClass'] = "";
            }
		   
              array_push($list,$data);
          }
          return $list;
      }

 
   
     /**
    * 获取  对象列表数据   合同评审
    */
    public function add_htreview()
    {
        $param = $this->request->param();
        
        if(empty($param['_id'])){
            file_put_contents('jindie.log', "请求结束！id不能为空".PHP_EOL, FILE_APPEND);
            $this->error("请求结束！id不能为空");
        }
        
	    file_put_contents('jindie.log', "接收crm传输的数据：".json_encode($param).PHP_EOL, FILE_APPEND);
        $id = $param["_id"];
    
		
        $qwe = $this->corpAccessToken();
        $url = 'https://open.fxiaoke.com/cgi/crm/custom/v2/data/query';
        $corpAccessToken = $qwe['corpAccessToken'];
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';
      
		 $data = [ 
            'search_query_info'=>[ 
                'offset'=>0, 
                'limit'=>100, 
                'filters'=>[
							[
								'field_name'=>'_id',
								'field_values'=>[$id],
								'operator'=>'EQ' 
							]
                        ]
                    ],'dataObjectApiName'=>'object_qdBZ2__c'];
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'));
       //  dump($res);die; 
        $method = 'POST';
         $header = [
                         'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
       
		file_put_contents('jindie.log', "请求crm获取合同评审接口的数据：".json_encode($dsdf).PHP_EOL, FILE_APPEND);
      
    //     表头	
    //     1    submitter	销售员
    //     2	contractNo	合同号
    //     3	projectName	项目名称
    //     4	contractNature	合同性质
    //     5	marketSegment1	市场领域（一级）
    //     6	targetMarket	避雷器目标市场细分
    //     7	qrCodeNameplate	二维码铭牌
    //     8	RFIDTag	RFID标签
    //     9	customerName	客户
    //     10	technicalPersonnel	技术人员
    //     11	otherRequire	其他要求
    // entry	
    //     12	materialNum	工厂代号
    //     13	promodel	产品型号
    //     14	num	数量
    //     15	trackNumberTxt	跟踪号
    //     16	techniComplete	技术完成日期
    //     17	produceComplete	生产完成日期
    //     18	materialReturn	物资回厂日期
    //     19	bomProperty	BOM属性
    //     20	externalInsulation	外绝缘部件号码
    //     21	relationBillNo	联系单编号
    //     22	bomBatch	BOM批次
    //     23	paintColor	油漆颜色
    //     24	basinColor	盆子颜色
    //     25	inAndOutDoor	户内/户外
    //     26	remark	备注
    //     27	detailNumber	明细序号
    //     28	productClass	产品分类
    //     29	voltageLevel	电压等级
    //     30	measurementUnit	计量单位
    //     31	unitPrice	单价
    //     32	amount	新签合同额
    //     33	isHasMonitor	是否有监测器
    //     34	monitorModel	监测器型号/计数器型号
    //     35	sparePartIdent	备品标识
    //     36	deliveryDate	交货期（预计）
    //     37	isPreProduct	是否已经投预
    //     38	objID	实物ID号码段
    //     39	packingListType	装箱单类型
    
     
        if($dsdf['errorCode'] == 0 && $dsdf['errorMessage'] == "OK"){//成功
            //重组数组
            $dataList = $dsdf['data']['dataList'];
            $data = [];
            foreach($dataList as $k=>$v){
  
              //  $field_iHwnt__c = date("Y-m-d H:i:s",substr($v['field_iHwnt__c'],0,10));
            
                $data[] = [

                    "dataid"=>$v['_id'],
                    "submitter"=>$v['owner'],//销售员
                    "contractNo"=>$v['name'],//合同号
                    "projectName"=>$v['field_326k4__c__r'],//项目名称
                    "contractNature"=>$v['field_J72W0__c'],//合同性质
                    "marketSegment1"=>$v['field_mZO04__c'],//市场领域（一级）
                    "targetMarket"=>$v['field_u0hPj__c'],//避雷器目标市场细分
                    "qrCodeNameplate"=>$v['field_p1yvB__c'],//二维码铭牌
                    "RFIDTag"=>$v['field_RZYBW__c'],//RFID标签
                    "customerName"=>$v['field_lXFxf__c__r'],//客户
                    "technicalPersonnel"=>$v['field_ye2h2__c'],//技术人员
                    "otherRequire"=>$v['field_F4xK7__c'],//其他要求
                ];
              
                //获取合同评审明细
                $row = $this->query($v['_id']);
                //合同评审数组和合同明细数组重组
                foreach($data as $key=>$val){
                    $val["entry"] = $row;
                    $data[$key] = $val;
                }
            
           
            }
            //技术人员  getByopenUserid  get_renyuan
            $flagsw = $this->getByopenUserid($data[0]['technicalPersonnel']);
            $get_renyuan = $this->get_renyuan($flagsw);
            if(!empty($get_renyuan)){
                $technicalPersonnel = implode(",",$get_renyuan); 
            }else{
                $technicalPersonnel = ""; 
            }
             //销售员
             $asdfss = $this->getByopenUseridxsy($data[0]['submitter']);
             if(!empty($asdfss)){
                 $submitter = implode(",",$asdfss); 
             }else{
                 $submitter = ""; 
             }
    
           //如果有数据那就传输
           if(!empty($data)){
                $data_f = [
                    "dataid"=>$data[0]['dataid'],
                    "submitter"=>$submitter,//销售员
                    "contractNo"=>$data[0]['contractNo'],//合同号
                    "projectName"=>$data[0]['projectName'],//项目名称
                    "contractNature"=>$data[0]['contractNature'],//合同性质
                    "marketSegment1"=>$data[0]['marketSegment1'],//市场领域（一级）
                    "targetMarket"=>$data[0]['targetMarket'],//避雷器目标市场细分
                    "qrCodeNameplate"=>$data[0]['qrCodeNameplate'],//二维码铭牌
                    "RFIDTag"=>$data[0]['RFIDTag'],//RFID标签
                    "customerName"=>$data[0]['customerName'],//客户
                    "technicalPersonnel"=>$technicalPersonnel,//技术人员
                    "otherRequire"=>$data[0]['otherRequire'],//其他要求
                    "json_data"=>json_encode($data[0]["entry"]),
                    "add_time"=>time()
                ];
            
              Db::name("contract_review")->insert($data_f);
              $contractId = Db::name('contract_review')->getLastInsID();

           }else{
                file_put_contents('jindie.log', "请求结束，数据为空".PHP_EOL, FILE_APPEND);
				return 2;
           }

           $data_h = [
                "submitter"=>$submitter,//销售员
                "contractNo"=>$data[0]['contractNo'],//合同号
                "projectName"=>$data[0]['projectName'],//项目名称
                "contractNature"=>$data[0]['contractNature'],//合同性质
                "marketSegment1"=>$data[0]['marketSegment1'],//市场领域（一级）
                "targetMarket"=>$data[0]['targetMarket'],//避雷器目标市场细分
                "qrCodeNameplate"=>$data[0]['qrCodeNameplate'],//二维码铭牌
                "RFIDTag"=>$data[0]['RFIDTag'],//RFID标签
                "customerName"=>$data[0]['customerName'],//客户
                "technicalPersonnel"=>$technicalPersonnel,//技术人员
                "otherRequire"=>$data[0]['otherRequire'],//其他要求
                "entry"=>$data[0]["entry"]
           ];
           //合同性质
           if($data_h['contractNature'] == "lS8ho4R41"){
                $data_h['contractNature'] = "常规";
            }elseif($data_h['contractNature'] == "option1"){
                    $data_h['contractNature'] = "重点";
            }else{
                $data_h['contractNature'] = "";
            }
            //市场领域（一级）
           if($data_h['marketSegment1'] == "Br4Md4Q7W"){
                $data_h['marketSegment1'] = "西电集团内配";
            }elseif($data_h['marketSegment1'] == "1tH8o29WI"){
                    $data_h['marketSegment1'] = "外部订货(网外)";
            }elseif($data_h['marketSegment1'] == "a7QP4zwyb"){
                $data_h['marketSegment1'] = "外部订货（网内）";
            }else{
                $data_h['marketSegment1'] = "";
            }
            //RFID标签
           if($data_h['RFIDTag'] == "pcq0Ix1dY"){
                $data_h['RFIDTag'] = "不需要";
            }elseif($data_h['RFIDTag'] == "iv5x652Wb"){
                    $data_h['RFIDTag'] = "需要,用户已提供ID编码";
            }elseif($data_h['RFIDTag'] == "lbCKk26GY"){
                $data_h['RFIDTag'] = "需要,用户尚未提供ID编码";
            }else{
                $data_h['RFIDTag'] = "";
            }
            //二维码铭牌
           if($data_h['qrCodeNameplate'] == "8saqalKL3"){
                $data_h['qrCodeNameplate'] = "不需要";
            }elseif($data_h['qrCodeNameplate'] == "pmt2v1QuH"){
                    $data_h['qrCodeNameplate'] = "需要,用户已提供ID编码";
            }elseif($data_h['qrCodeNameplate'] == "pIffm15Ix"){
                $data_h['qrCodeNameplate'] = "需要,用户尚未提供ID编码";
            }else{
                $data_h['qrCodeNameplate'] = "";
            }
            //避雷器目标市场细分
           if($data_h['targetMarket'] == "1v2vvQ1dx"){
                $data_h['targetMarket'] = "国网";
            }elseif($data_h['targetMarket'] == "G81Ri16dW"){
                    $data_h['targetMarket'] = "南网";
            }elseif($data_h['targetMarket'] == "70Lz0p6xr"){
                $data_h['targetMarket'] = "西电平台";
            }elseif($data_h['targetMarket'] == "85r1l4yMb"){
                $data_h['targetMarket'] = "间接出口";
            }elseif($data_h['targetMarket'] == "M2aN4cnlD"){
                $data_h['targetMarket'] = "直接出口";
            }elseif($data_h['targetMarket'] == "8tz6do2zU"){
                $data_h['targetMarket'] = "集团内配";
            }elseif($data_h['targetMarket'] == "kl6gfC5c4"){
                $data_h['targetMarket'] = "CEE内部(除西电集团)";
            }elseif($data_h['targetMarket'] == "050rj8Kwl"){
                $data_h['targetMarket'] = "CEE外部";
            }elseif($data_h['targetMarket'] == "2rn6du55Q"){
                $data_h['targetMarket'] = "国网集采、协议库存";
            }elseif($data_h['targetMarket'] == "hnTNf1Hci"){
                $data_h['targetMarket'] = "南网批次、协议库存";
            }elseif($data_h['targetMarket'] == "SP0uapBPc"){
                $data_h['targetMarket'] = "中压市场";
            }elseif($data_h['targetMarket'] == "99fz8dX2l"){
                $data_h['targetMarket'] = "电阻片市场";
            }elseif($data_h['targetMarket'] == "elz4dn9GJ"){
                $data_h['targetMarket'] = "其他市场";
            }else{
                $data_h['targetMarket'] = "";
            }
           // dump($data_h);die; 

           $url = 'http://192.168.0.11:9001/plm/order/createOrder';
 
           $res =  json_encode($data_h,JSON_UNESCAPED_UNICODE);
          // dump($res);die; 
           $method = 'POST';
           $header = [
                'Content-Type:application/json'
            ];
           $dsdfqwe = $this->http_curlnew($url,$method, $res, $header, $timeout = 10);
           //dump($dsdfqwe);die;
           if($dsdfqwe){
                Db::name('contract_review')->where("id",$contractId)->update(["status"=>1]);
                file_put_contents('jindie.log', "请求crm获取合同评审同步成功：".json_encode($dsdfqwe).PHP_EOL, FILE_APPEND);
                return 1;
           }else{
                Db::name('contract_review')->where("id",$contractId)->update(["status"=>2]);
                file_put_contents('jindie.log', "请求crm获取合同评审同步失败：".json_encode($dsdfqwe).PHP_EOL, FILE_APPEND);
                return -1;
           }
        }
        
    }


    //合同变更修改
    public function edit_htreview(){
        $param = $this->request->param();
        
        if(empty($param['_id'])){
            file_put_contents('jindie.log', "请求结束！合同变更id不能为空".PHP_EOL, FILE_APPEND);
            $this->error("请求结束！id不能为空");
        }
        
	    file_put_contents('jindie.log', "接收crm传输的合同变更数据：".json_encode($param).PHP_EOL, FILE_APPEND);
        $id = $param["_id"];
        
		
        $qwe = $this->corpAccessToken();
        $url = 'https://open.fxiaoke.com/cgi/crm/custom/v2/data/query';
        $corpAccessToken = $qwe['corpAccessToken'];
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_C508A03A3F8C43C1155D5816CF702B34';
      
		 $data = [ 
            'search_query_info'=>[ 
                'offset'=>0, 
                'limit'=>100, 
                'filters'=>[
							[
								'field_name'=>'_id',
								'field_values'=>[$id],
								'operator'=>'EQ' 
							]
                        ]
                    ],'dataObjectApiName'=>'object_as5y8__c'];
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'));
       //  dump($res);die; 
        $method = 'POST';
         $header = [
                         'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
        
		file_put_contents('jindie.log', "请求crm获取合同变更接口的数据：".json_encode($dsdf).PHP_EOL, FILE_APPEND);
      
       
//表头   object_as5y8__c	合同变更单
// 	2	name	合同变更单编号
// 	3	owner	销售员
// 	4	field_tJK2l__c	变更日期
// 	5	field_21C8P__c	注销日期
// 	6	field_Z1r12__c	合同评审单编号
// 	7	field_L4C2p__c	情况说明
// 	8	record_type	业务类型
// 	9	field_pj331__c	产品是否入库
// 		
// entry	field_rx8D6__c	合同明细
//  record_type	业务类型(只传输变更后的)
// 	11	field_5sgn7__c	跟踪号
// 	12	field_6wshK__c	交货期
// 	13	field_vGl2D__c	合同金额（元）
// 	14	field_91Hqs__c	产品数量
// 	15	field_faqJ1__c	产品型号
// 	16	field_3g11a__c	是否有监测器
// 	17	field_O31OR__c	监测器型号/计数器型号
// 	18	field_z1WhU__c	工厂代号
// 	19	field_M616j__c	监测器工厂代号
// 	20	field_6MDbq__c	油漆颜色
// 	21	field_Nhd76__c	避雷器工程BOM/标准BOM
// 	22	field_jBst7__c	监测器工程BOM/标准BOM
// 	23	field_qpHQm__c	户内/户外
// 	24	field_PkEk8__c	盆子颜色
// 	25	field_v61hO__c	装箱单类型
// 	26	field_x7x8k__c	其他要求
        if($dsdf['errorCode'] == 0 && $dsdf['errorMessage'] == "OK"){//成功
            //重组数组
            $dataList = $dsdf['data']['dataList'];
            $data = [];
            foreach($dataList as $k=>$v){
   
                $data[] = [
                    "dataid"=>$v['_id'],
                    "name"=>$v['name'],//合同变更单编号
                    "owner"=>$v['owner'],//销售员
                    "field_tJK2l__c"=>!empty($v['field_tJK2l__c']) ? $v['field_tJK2l__c'] :'',//变更日期
                    "field_21C8P__c"=>!empty($v['field_21C8P__c']) ? $v['field_21C8P__c'] :'',//注销日期
                    "field_Z1r12__c"=>$v['field_Z1r12__c__r'],//合同评审单编号
                    "field_L4C2p__c"=>$v['field_L4C2p__c'],//情况说明
                    "record_type"=>$v['record_type'],//业务类型
                    "field_pj331__c"=>!empty($v['field_pj331__c']) ? $v['field_pj331__c'] :'',//产品是否入库
                ];
           
                //获取合同变更明细
                $row = $this->bgquery($v['_id']);
                //合同评审数组和合同明细数组重组
                foreach($data as $key=>$val){
                    $val["entry"] = $row;
                    $data[$key] = $val;
                }
            
           
            }
            
            //销售员
            $asdfss = $this->getByopenUseridxsy($data[0]['owner']);
            if(!empty($asdfss)){
                $submitter = implode(",",$asdfss); 
            }else{
                $submitter = ""; 
            }
 
           //如果有数据那就传输
           if(!empty($data)){
            if(!empty($data[0]['field_tJK2l__c'])){
                $field_tJK2l__c = date("Y-m-d H:i:s",substr($data[0]['field_tJK2l__c'],0,10));//变更日期
            }else{
                $field_tJK2l__c = "";
            }
            if(!empty($data[0]['field_21C8P__c'])){
                $field_21C8P__c = date("Y-m-d H:i:s",substr($data[0]['field_21C8P__c'],0,10));//注销日期
            }else{
                $field_21C8P__c = "";
            }
             
                $data_bf = [
                    "dataid"=>$data[0]['dataid'],
                    "name"=>$data[0]['name'],//合同变更单编号
                    "owner"=>$submitter,//销售员
                    "field_tJK2l__c"=>$field_tJK2l__c,//变更日期
                    "field_21C8P__c"=>$field_21C8P__c,//注销日期
                    "field_Z1r12__c"=>$data[0]['field_Z1r12__c'],//合同评审单编号
                    "field_L4C2p__c"=>$data[0]['field_L4C2p__c'],//情况说明
                    "record_type"=>$data[0]['record_type'],//业务类型
                    "field_pj331__c"=>$data[0]['field_pj331__c'],//产品是否入库
                    "json_data"=>json_encode($data[0]["entry"]),
                    "add_time"=>time()
                ];
            
              Db::name("contract_review_bg")->insert($data_bf);
              $contractbgId = Db::name('contract_review_bg')->getLastInsID();

           }else{
                file_put_contents('jindie.log', "请求结束，数据为空".PHP_EOL, FILE_APPEND);
				return 2;
           }

           $data_d = [
                "name"=>$data[0]['name'],//合同变更单编号
                "owner"=>$submitter,//销售员
                "field_tJK2l__c"=>$field_tJK2l__c,//变更日期
                "field_21C8P__c"=>$field_21C8P__c,//注销日期
                "field_Z1r12__c"=>$data[0]['field_Z1r12__c'],//合同评审单编号
                "field_L4C2p__c"=>$data[0]['field_L4C2p__c'],//情况说明
                "record_type"=>$data[0]['record_type'],//业务类型
                "field_pj331__c"=>$data[0]['field_pj331__c'],//产品是否入库
                "entry"=>$data[0]["entry"]
           ];
     
            //业务类型
            if($data_d['record_type'] == "default__c"){
                $data_d['record_type'] = "合同变更";
            }elseif($data_d['record_type'] == "record_y1KOg__c"){
                    $data_d['record_type'] = "合同注销";
            }else{
                $data_d['record_type'] = "";
            }
            
            //产品是否入库
           if($data_d['field_pj331__c'] == "HFpyleq1D"){
                $data_d['field_pj331__c'] = "是";
            }elseif($data_d['field_pj331__c'] == "option1"){
                    $data_d['field_pj331__c'] = "否";
            }else{
                $data_d['field_pj331__c'] = "";
            }
            //dump($data_d);die; 
           $url = 'http://192.168.0.11:9001/plm/order/updateOrder';
 
           $res =  json_encode($data_d,JSON_UNESCAPED_UNICODE);
          // dump($res);die; 
           $method = 'POST';
           $header = [
                'Content-Type:application/json'
            ];
           $dsdfbgd = $this->http_curlnew($url,$method, $res, $header, $timeout = 10);
           //dump($dsdfbgd);die;
           if($dsdfbgd){
                Db::name('contract_review_bg')->where("id",$contractbgId)->update(["status"=>1]);
                file_put_contents('jindie.log', "接收crm传输的合同变更同步成功：".json_encode($dsdfbgd).PHP_EOL, FILE_APPEND);
                return 1;
           }else{
                Db::name('contract_review_bg')->where("id",$contractbgId)->update(["status"=>2]);
                file_put_contents('jindie.log', "接收crm传输的合同变更同步失败：".json_encode($dsdfbgd).PHP_EOL, FILE_APPEND);
                return -1;
           }
        } 
    }

 
    
   /**
    * 发送 post 请求 
    * @access protected
    * @return string
    */
 
   
    protected function http_curl($url, $method = 'POST', $data = array(), $header, $timeout = 10)
   {
       $curl = curl_init($url);
       $method = strtoupper($method);
       //请求方式啥
       curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
       //post请求
       if ($method == 'POST') curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
       //超时时间
       curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
       //设置header头
       // if ($header !== false) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
       curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 
       
       curl_setopt($curl, CURLOPT_FAILONERROR, false);
       //返回抓取数据
       curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
       //输出header头信息
       curl_setopt($curl, CURLOPT_HEADER, true);
       //TRUE 时追踪句柄的请求字符串，从 PHP 5.1.3 开始可用。这个很关键，就是允许你查看请求header
       curl_setopt($curl, CURLINFO_HEADER_OUT, true);

       //https请求
       if (1 == strpos("$" . $url, "https://")) {
           curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
           curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
       }
       $curlError = curl_error($curl);
       list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
       $status = $status;
       $headerStr = trim(substr($content, 0, $status['header_size']));
       $content = trim(substr($content, $status['header_size']));
        $cont = json_decode($content,true);
        
       //  $cont['headers'] =$headerStr;   //返回的头部信息去掉
        return $cont;

   }

   /**
    * 发送 post 请求 
    * @access protected
    * @return string
    */
 
   
    protected function http_curlnew($url, $method = 'POST', $data = array(), $header, $timeout = 10)
   {
       $curl = curl_init($url);
       $method = strtoupper($method);
       //请求方式啥
       curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
       //post请求
       if ($method == 'POST') curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
       //超时时间
       curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
       //设置header头
       // if ($header !== false) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
       curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 
       
       curl_setopt($curl, CURLOPT_FAILONERROR, false);
       //返回抓取数据
       curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
       //输出header头信息
       curl_setopt($curl, CURLOPT_HEADER, true);
       //TRUE 时追踪句柄的请求字符串，从 PHP 5.1.3 开始可用。这个很关键，就是允许你查看请求header
       curl_setopt($curl, CURLINFO_HEADER_OUT, true);

       //https请求
       if (1 == strpos("$" . $url, "https://")) {
           curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
           curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
       }
       $curlError = curl_error($curl);
    
       list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
       $status = $status;
       $headerStr = trim(substr($content, 0, $status['header_size']));
       $content = trim(substr($content, $status['header_size']));
      
        $cont = json_decode($content,true);
       //  $cont['headers'] =$headerStr;   //返回的头部信息去掉
        return $cont;

   }
 

 
}


